//
//  Textfield+Extension.swift
//  IMIHome
//
//  Created by Roffa Zhou on 2021/9/7.
//  Copyright © 2021 上海创米科技有限公司. All rights reserved.
//

import Foundation
import UIKit

public extension UITextField {
    
    /**简单通过响应链解耦实现textfield键盘出现后，位置调整*/
    func listen(){
        NotificationCenter.default.addObserver(self, selector: #selector(ls_begin), name: UITextField.textDidBeginEditingNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ls_end), name: UITextField.textDidEndEditingNotification, object: nil)        
    }
    
    /// 找到当前textfield所在的viewcontroller.view的一级子视图
    /// - Returns: 返回找到的视图
    private func frameView()->UIView{
        var view = self.superview
        while view != nil, view?.superview != self.viewController?.view {
            view = view!.superview
        }
        return view!
    }
    
    /// 键盘将要展开
    @objc private func ls_begin(){
        if self.viewController?.view.transform == .identity {
            if self.viewController!.view.viewWithTag(2021090700) == nil {  //增加一层遮罩
                let coverView = UIView()
                coverView.tag = 2021090700
                self.viewController!.view.addSubview(coverView)
                coverView.isUserInteractionEnabled = true
                coverView.snp.makeConstraints { make in
                    make.left.top.right.equalTo(0)
                    make.bottom.equalTo(self.snp.top)
                }
                coverView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(closeKeyboard)))
            }
            UIView.animate(withDuration: 0.3) {
                self.frameView().transform = CGAffineTransform(translationX: 0, y: self.viewController!.view.height - self.frameView().maxY - 320)
            }
        }
    }
    @objc private func ls_end(){
        UIView.animate(withDuration: 0.3) {
            self.frameView().transform = CGAffineTransform.identity
        }
    }
    @objc private func closeKeyboard(){
        resignFirstResponder()
        let view = self.viewController!.view.viewWithTag(2021090700)
        if view != nil {
            view!.removeFromSuperview()
        }
    }
}
//MARK: - 限制输入长度，自动考虑中英文
public extension UITextField {
    fileprivate struct AssociatedKeys {
        static var maxWords: String = "maxWords"
        static var bAddChangNotif: String = "bAddChangNotif"
    }

    private var bAddChangNotif: Bool{  //是否已增加监听输入改变通知
        get { objc_getAssociatedObject(self, &AssociatedKeys.bAddChangNotif) as? Bool ?? false }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.bAddChangNotif, newValue, .OBJC_ASSOCIATION_ASSIGN)
        }
    }
    public var maxWords: Int{  //以中文字数为判断标准，其他语言用中文转换为字节数限制
        get { objc_getAssociatedObject(self, &AssociatedKeys.maxWords) as? Int ?? 0 }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.maxWords, newValue, .OBJC_ASSOCIATION_ASSIGN)
            if !bAddChangNotif {
                NotificationCenter.default.addObserver(self, selector: #selector(textViewChanged), name: UITextField.textDidChangeNotification, object: nil)
                bAddChangNotif = true
            }
        }
    }
    private func maxBytes(_ max: Int = 0) -> Int {  //转换为对应的字节数
        if max > 0 {
            return max * "锋".data.count
        }
        return maxWords * "锋".data.count
    }
    /// 获取当前输入长度，去除选中部分(如拼音输入、自动填充)
    /// author rf/2021-10-29
    public func currentCount() -> Int{
        var count = text?.count ?? 0
        if markedTextRange != nil {
            let markedCount = offset(from: markedTextRange!.start, to: markedTextRange!.end)
            if count > markedCount {
                count -= markedCount
            }
        }
        return count
    }
    
    @objc func textViewChanged(){
        var newText = String(text!.prefix(currentCount()))
        if maxWords > 0, newText.data.count > maxBytes() {  //输入的文字信息已经超过最大限制
            //控制最大输入, 加入当前字符后超限，删除新增的字符
            newText.removeLast()
            text = newText
        }
    }
    
    /// 输入框输入的字符是否超过最大输入限制
    /// - Parameter max: 允许最大输入数.  max为中文对应的文字数， 英文或表情计算结果为字节标准
    ///  - Authors: rf/2021-11-04
    public func isOverload(_ max: Int) -> Bool{
        var current = 0
        if let str = text {
            return str.data.count > maxBytes(max)
        }else{
            return false
        }
    }
}
